package com.xhwl.centiotdata.utils;

import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @Author: luyi
 * @Description:
 * @Date: Create in 2:25 下午 2020/7/16
 */
public class StrUtils extends org.apache.commons.lang3.StringUtils {

    public static boolean isEmpty(String str) {
        return null == str || 0 == str.length();
    }

    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    public static List strToArr(String str, String split) {
        if (StrUtils.isBlank(str)) {
            return Lists.newArrayList();
        }
        return Arrays.asList((str.split(split)));
    }

    public static String arrToStr(List arr, String split) {
        if (CollectionUtils.isEmpty(arr)) {
            return "";
        }
        return StrUtils.join(arr, split);
    }

    public static List strToArr(String str) {
        return strToArr(str, ",");
    }

    public static String arrToStr(List arr) {
        return arrToStr(arr, ",");
    }

    public static String toUtf8String(String str) {
        try {
            return new String(str.getBytes("gbk"), StandardCharsets.UTF_8);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 在使用正则表达式时，利用好其预编译功能，可以有效加快正则匹配速度
     * 判断string类型为是数字
     */
    private static final Pattern PATTERN = Pattern.compile("-?[0-9]+.?[0-9]*");
    /**
     * 判断字符串是否是数字型
     * @param str
     * @return 正确匹配返回true-数字类型的字符串
     */
    public static boolean isNumber(String str){
        if (org.springframework.util.StringUtils.isEmpty(str)) {
            return false;
        }
        return PATTERN.matcher(str).matches();
    }

    private static final String zeroStr = "0.00";

    /**
     *
     * @param str 数字类型字符串
     * @return 带两位小数点的Double/返回默认0.00
     */
    public static BigDecimal strToDB(String str){
        if (isNumber(str)) {
            return new BigDecimal(str).setScale(2, RoundingMode.HALF_UP);
        } else {
            return new BigDecimal(zeroStr);
        }
    }

    public static BigDecimal strCoverBD(String str) {
        BigDecimal bd;
        try {
            bd = new BigDecimal(str);
        } catch (Exception e) {
            bd = BigDecimal.ZERO;
        }
        return bd.setScale(2, RoundingMode.HALF_UP);
    }

    public static void main(String[] args) {

        BigDecimal todayPower = new BigDecimal("100.521");
        BigDecimal power1 = new BigDecimal("0.521");
        System.out.println(todayPower.subtract(power1).setScale(2, RoundingMode.HALF_UP));
    }

}
